package io;

import java.io.*;
import java.util.Scanner;

public class Demo13 {
    public static void main(String[] args) {
        Scanner scanner= new Scanner(System.in);
        System.out.println("请输入要搜索的路径:");
        String path= scanner.next();
        System.out.println("请输入要查询的词:");
        String searchWord=scanner.next();
        File fileFile= new File(path);
        if (!fileFile.isDirectory()){
            System.out.println("当前输入的路径非法!");
            return;
        }
        search(fileFile,searchWord);
    }

    private static void search(File fileFile, String searchWord) {
        File[] files= fileFile.listFiles();
        if (files==null){
            //空目录,递归的条件结束
            return;
        }
        for(File f:files){
            if (f.isFile()){
                //读取文件内容并搜索
                marchWord(f,searchWord);
            }else if (f.isDirectory()){
                search(f,searchWord);
            }
        }
    }

    //复制针对一个文件进行读取和判定
    private static void marchWord(File f, String searchWord) {
        try(Reader reader= new FileReader(f)){
            //把读到的结果,最终构造到一个StringBuilder里
            StringBuilder stringBuilder=new StringBuilder();
            while (true){
                int c= reader.read();
                if (c==-1){
                    break;
                }
                stringBuilder.append((char) c);
            }
            //循环结束.此时所有的文件内容都写入到了stringBuilder里
            if (stringBuilder.indexOf(searchWord)>=0){
                //找到了
                System.out.println("找到了匹配的结果"+f.getAbsoluteFile());
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
